#!/usr/bin/env python
# -*- coding: utf8 -*-

import os
from qtpy import QtGui
from .frameless_resizeable_widget import FramelessResizeableWidget
from .ui.smart_window import Ui_Form
from .get_style import get_style
import yaml

class SmartWindow(FramelessResizeableWidget):
    def __init__(self, parent=None):
        super(SmartWindow, self).__init__(parent)
        self._ui = Ui_Form()
        self._ui.setupUi(self)
        self._ui.title._parent = self
        self._ui.verticalLayout.setContentsMargins(5, 5, 5, 5)
        self.set_icon(':/icons/smart_logo.png')
        self._ui.widget.enterEvent = self.widget_enter_event
        self._ui.title._ui.theme_btn.toggled.connect(self.on_theme_btn_toggled)

        self.title_icon = self._ui.title._ui.icon_btn
        self.set_title_icon_enabled(0)
        # self.setStyle(QtWidgets.QApplication.style())
        self.__init_style()

    def __init_style(self):
        _theme = self.get_cached_theme()
        if _theme == 'moon':
            self._ui.title._ui.theme_btn.setChecked(0)
            self.setStyleSheet(get_style('moon'))
        elif _theme == 'sun':
            self._ui.title._ui.theme_btn.setChecked(1)
            self.setStyleSheet(get_style('sun'))


    def set_title_icon_enabled(self, status):
        self.title_icon.setEnabled(status)

    def get_user_config(self):
        _smart_root = os.path.join(os.path.expanduser('~'), 'smart').replace('\\', '/')
        _config = os.path.join(_smart_root, 'config.yml').replace('\\', '/')
        if not os.path.isdir(_smart_root):
            os.makedirs(_smart_root)
        return _config

    def get_cached_theme(self):
        _config = self.get_user_config()
        if os.path.isfile(_config):
            with open(_config) as f:
                data = yaml.safe_load(f)
            if data and isinstance(data, dict):
                return data.get('theme', 'moon')

        return 'moon'

    def set_cached_theme(self, theme):
        _config = self.get_user_config()
        data = {'theme':theme}
        with open(_config, 'w') as f:
            yaml.safe_dump(data, f)

    def on_theme_btn_toggled(self, status):
        if status:
            self.setStyleSheet(get_style('sun'))
            self.set_cached_theme('sun')
        else:
            self.setStyleSheet(get_style('moon'))
            self.set_cached_theme('moon')

    def set_title(self, text):
        self.setWindowTitle(text)
        self._ui.title.set_window_title(text)

    def set_icon(self, path):
        self._ui.title.set_icon(path)
        _icon = QtGui.QIcon()
        _icon.addPixmap(QtGui.QPixmap(path), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(_icon)

    def widget_enter_event(self, event):
        self.set_default()